// ============================================================================
// 简化的数据查询 Hook - 解决循环依赖问题
// ============================================================================

import { useState, useEffect, useCallback, useRef } from 'react'
import { dataService } from '../services'
import { logger } from '../utils/logger'

// ============================================================================
// 类型定义
// ============================================================================

export interface SimpleQueryOptions {
  enabled?: boolean
  cacheTime?: number
  retry?: number
}

export interface SimpleQueryResult<T> {
  data: T | null
  loading: boolean
  error: Error | null
  refetch: () => Promise<void>
}

// ============================================================================
// 简单缓存
// ============================================================================

const simpleCache = new Map<string, { data: any; timestamp: number; ttl: number }>()

function getCached<T>(key: string): T | null {
  const cached = simpleCache.get(key)
  if (!cached) return null
  
  if (Date.now() - cached.timestamp > cached.ttl) {
    simpleCache.delete(key)
    return null
  }
  
  return cached.data
}

function setCache<T>(key: string, data: T, ttl: number): void {
  simpleCache.set(key, {
    data,
    timestamp: Date.now(),
    ttl
  })
}

// ============================================================================
// 简化的查询 Hook
// ============================================================================

export function useSimpleQuery<T>(
  key: string,
  queryFn: () => Promise<T>,
  options: SimpleQueryOptions = {}
): SimpleQueryResult<T> {
  const {
    enabled = true,
    cacheTime = 30000, // 30秒缓存
    retry = 1
  } = options

  const [data, setData] = useState<T | null>(() => getCached<T>(key))
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<Error | null>(null)
  
  const queryLogger = logger
  const mountedRef = useRef(true)
  const retryCountRef = useRef(0)
  const isExecutingRef = useRef(false)

  // 执行查询
  const executeQuery = useCallback(async (force = false) => {
    if (!enabled || !mountedRef.current || isExecutingRef.current) return

    // 检查缓存
    if (!force) {
      const cached = getCached<T>(key)
      if (cached !== null) {
        setData(cached)
        setError(null)
        return
      }
    }

    isExecutingRef.current = true
    setLoading(true)
    setError(null)

    try {
      queryLogger.debug('执行查询')
      const result = await queryFn()
      
      if (!mountedRef.current) return

      setData(result)
      setError(null)
      retryCountRef.current = 0
      
      // 缓存结果
      setCache(key, result, cacheTime)
      
      queryLogger.debug('查询成功')
      
    } catch (err) {
      if (!mountedRef.current) return

      const error = err as Error
      queryLogger.error('查询失败', error)

      // 简单重试
      if (retryCountRef.current < retry) {
        retryCountRef.current++
        setTimeout(() => {
          if (mountedRef.current) {
            isExecutingRef.current = false
            executeQuery(force)
          }
        }, 1000)
        return
      }

      setError(error)
    } finally {
      if (mountedRef.current) {
        setLoading(false)
      }
      isExecutingRef.current = false
    }
  }, [enabled, key, queryFn, cacheTime, retry, queryLogger])

  // 手动刷新
  const refetch = useCallback(async () => {
    retryCountRef.current = 0
    await executeQuery(true)
  }, [executeQuery])

  // 初始化
  useEffect(() => {
    mountedRef.current = true
    
    if (enabled) {
      executeQuery()
    }

    return () => {
      mountedRef.current = false
      isExecutingRef.current = false
    }
  }, [key, enabled]) // 只依赖key和enabled

  return {
    data,
    loading,
    error,
    refetch
  }
}

// ============================================================================
// 预定义的查询Hooks
// ============================================================================

/**
 * 获取账号列表
 */
export function useAccountsQuery() {
  return useSimpleQuery(
    'accounts',
    () => dataService.getAccounts(),
    { cacheTime: 30000 }
  )
}

/**
 * 获取任务列表
 */
export function useTasksQuery() {
  return useSimpleQuery(
    'tasks',
    () => dataService.getTasks(),
    { cacheTime: 30000 }
  )
}

/**
 * 获取配置
 */
export function useConfigQuery() {
  return useSimpleQuery(
    'config',
    () => dataService.getConfig(),
    { cacheTime: 60000 }
  )
}

/**
 * 获取统计信息
 */
export function useStatsQuery(enabled = true) {
  return useSimpleQuery(
    'stats',
    () => dataService.getStats(),
    { 
      enabled,
      cacheTime: 30000,
      retry: 0 // 统计信息失败不重试
    }
  )
}

/**
 * 清理缓存
 */
export function clearQueryCache(pattern?: string): void {
  if (pattern) {
    for (const key of simpleCache.keys()) {
      if (key.includes(pattern)) {
        simpleCache.delete(key)
      }
    }
  } else {
    simpleCache.clear()
  }
}
